from rest_framework import serializers
from ..models.admin import *
from datetime import datetime


# 管理员
class FaAdminSerializer(serializers.ModelSerializer):
    status_display = serializers.CharField(
        source='get_status_display',
        read_only=True,
        help_text='状态显示值'
    )
    login_datetime = serializers.SerializerMethodField(
        help_text='格式化登录时间'
    )
    create_datetime = serializers.SerializerMethodField(
        help_text='格式化创建时间'
    )
    update_datetime = serializers.SerializerMethodField(
        help_text='格式化更新时间'
    )

    class Meta:
        model = FaAdmin
        fields = '__all__'
        extra_kwargs = {
            'password': {'write_only': True},
            'salt': {'write_only': True},
            'token': {'write_only': True},
        }

    def validate(self, data):
        # 自定义验证逻辑
        if len(data.get('mobile', '')) != 11:
            raise serializers.ValidationError("手机号必须为11位")
        return data


# 管理员分组
class FaAuthGroupSerializer(serializers.ModelSerializer):
    status_display = serializers.CharField(
        source='get_status_display',
        read_only=True,
        help_text='状态显示值'
    )
    create_datetime = serializers.SerializerMethodField(
        help_text='格式化创建时间'
    )
    update_datetime = serializers.SerializerMethodField(
        help_text='格式化更新时间'
    )
    rules_list = serializers.ListField(
        child=serializers.IntegerField(),
        source='rules_list',
        help_text='规则ID列表'
    )

    class Meta:
        model = FaAuthGroup
        fields = '__all__'
        extra_kwargs = {
            'rules': {'write_only': True},
        }

    def validate_rules(self, value):
        """验证规则格式"""
        try:
            [int(rule_id) for rule_id in value.split(',') if rule_id]
        except ValueError:
            raise serializers.ValidationError("规则ID必须为整数")
        return value


# 管理员分组关联
class FaAuthGroupAccessSerializer(serializers.ModelSerializer):
    user_info = serializers.SerializerMethodField(help_text='用户信息')
    group_info = serializers.SerializerMethodField(help_text='组信息')

    class Meta:
        model = FaAuthGroupAccess
        fields = ['uid', 'group_id', 'user_info', 'group_info']
        extra_kwargs = {
            'uid': {'required': True},
            'group_id': {'required': True},
        }


# 日志记录
class FaAdminLogSerializer(serializers.ModelSerializer):
    class Meta:
        model = FaAdminLog
        fields = '__all__'
        extra_kwargs = {
            'content': {'write_only': False},  # 根据安全需求调整
            'useragent': {'write_only': True},
        }

    def validate(self, data):
        """验证数据"""
        if len(data.get('title', '')) > 100:
            raise serializers.ValidationError("标题长度不能超过100字符")
        return data
